<!-- 商城 -->
<script setup>
import { reactive, ref, nextTick } from 'vue'
import { onLoad, onShow, onPageScroll, onReachBottom } from '@dcloudio/uni-app'
// import { random, guid } from '@/uni_modules/uview-plus';
import { getBannerListApi, getNowActivityApi, getCategoryListApi, getSpuListApi } from '@/api/shop.js'
import { secondsUntilTargetTime, numberUnify } from '@/utils'
// 数据
const info = reactive({
  barHeight: 0,
  navHeight: 0,
  userId: '',
  isInTop: true,
  bannerList: [],
  timeData: null,
  activityShopList: [],
  categoryId: '',
  pageNo: 1, // 当前页码
  pageSize: 10, // 每页数量
  totalPages: 10 // 总页数
})
// 监听滚动
onPageScroll(res => {
  info.isInTop = res.scrollTop < 50

})
// 获取手机状态栏高度
onLoad(() => {
  //获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
  let { statusBarHeight } = uni.getSystemInfoSync()
  info.barHeight = statusBarHeight
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  info.navHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) * 2
  getCategoryList()
  getList()
})

// 初始化
onShow(() => {
  info.userId = uni.getStorageSync('userId');
  getBannerList()
  getNowActivity()
})
// 校验是否用户已登录
const checkLogin = () => {
  if (info.userId === '') {
    goLoginPage()
    return false
  }
}
// 前往登录页面
function goLoginPage() {
  uni.navigateTo({
    url: '/pages/login/index'
  })
}
// 获取轮播列表数据
function getBannerList() {
  getBannerListApi({
    position: '3'
  })
    .then(res => {
      // console.log('res', res);
      info.bannerList = res.data
      // console.log(info.bannerList)
    })
}
// 点击轮播
function swiperClick(i) {
  // console.log('item', item)
  const item = info.bannerList[i]
  // 前往商品详情页
  // uni.navigateTo({ url: item.url })
}

// 获取当前秒杀活动
function getNowActivity() {
  getNowActivityApi({})
    .then(res => {
      // console.log('res', res);
      const { activities, config } = res.data

      // 计算秒杀剩余时间
      info.timeData = secondsUntilTargetTime(config.endTime)
      // 更新活动商品列表
      activities.forEach(shop => {
        shop.marketPrice = numberUnify(shop.marketPrice / 100)
        shop.seckillPrice = numberUnify(shop.seckillPrice / 100)
      });
      info.activityShopList = activities
    })
}
// 倒计时数据--展示
const timeData = ref({});

// 活动倒计时实时数据
const onChange = (e) => {
  timeData.value = e;
};
// 活动倒计时结束 --获取最新活动信息
function onActivityend() {
  getNowActivity()
}


// 商品tabs数据
const tabsList = reactive([
  { id: '', name: '全部' }
]);
// 获取商品分类列表
function getCategoryList() {
  getCategoryListApi({})
    .then(res => {
      // console.log('res', res);
      res.data.forEach(item => {
        tabsList.push({
          id: item.id,
          name: item.name
        })
      });
    })
}
// 点击tabs切换
function tabsChange(item) {
  // console.log('item', item);
  info.categoryId = item.id
  info.pageNo = 1
  getList()
}
// 商品数据
const shopInfo = {
  loadStatus: 'loadmore'
}
// 列表数据
const flowList = ref([])
// 瀑布流对象
const uWaterfallRef = ref(null);
// 获取列表
function getList() {
  shopInfo.loadStatus = 'loading';
  getSpuListApi({
    pageNo: info.pageNo,
    pageSize: info.pageSize,
    categoryId: info.categoryId
  })
    .then(res => {
      // console.log('res', res);
      const { list, total } = res.data
      info.totalPages = Math.ceil(total / info.pageSize)
      list.forEach(item => {
        item.marketPrice = numberUnify(item.marketPrice / 100)
        item.price = numberUnify(item.seckillPrice / 100)
      })
      if (info.pageNo === 1) {
        uWaterfallRef.value.clear()
        nextTick().then(() => {
          flowList.value = list
        });
        console.log('切换tabs后数据', info.pageNo, flowList.value)
      } else {
        flowList.value = [...flowList.value, ...list]
      }
      info.pageNo++;
      shopInfo.loadStatus = info.pageNo >= info.totalPages ? 'nomore' : 'loadmore'
    })
}
// 监听页面滚动到底部
onReachBottom(() => {
  if (shopInfo.loadStatus !== 'loadmore') return
  getList()
})
// 前往商品详情页面
function goProductDetail(id) {
  checkLogin()
  uni.navigateTo({
    url: '/subPackage/shop/detail?id=' + id
  })
}
// 前往活动商品详情页面
function goActivityProductDetail(item) {
  checkLogin()
  uni.navigateTo({
    url: `/subPackage/shop/detail?id=${item.spuId}&type=1&activityId=${item.id}`
  })
}
// 前往搜索页面
function goSearch() {
  uni.navigateTo({
    url: '/subPackage/shop/seach'
  })
}
// 前往购物车页面
function goShoppingCart() {
  checkLogin()
  // console.log('goShoppingCart');
  uni.navigateTo({
    url: '/subPackage/shop/shoppingCart/index'
  })
}
// 前往抽奖页面
function goBindBox() {
  checkLogin()
  uni.navigateTo({
    url: '/subPackage/shop/blindBox/index'
  })
}
// 前往限时抢购页面
function goFlashSale() {
  uni.navigateTo({
    url: '/subPackage/shop/flashSale/index'
  })
} 
</script>

<template>
  <view class="shop-page">
    <!-- 导航栏 -->
    <view class="navber"
      :style="{ 'padding-top': info.barHeight + 'px', 'backgroundColor': !info.isInTop ? '#000' : 'transparent' }">
      <view class="tag-box">
        <image src="/static/images/icons/shop_seach.png" mode="scaleToFill" style="width:48rpx; height:48rpx;"
          @click="goSearch" />
        <image src="/static/images/icons/shop_car.png" mode="scaleToFill" style="width:48rpx; height:48rpx;"
          @click="goShoppingCart" />
      </view>
      <!-- 标题栏 -->
      <view class="title" :style="{ 'height': info.navHeight + 'px' }"><text>千岛季商城</text></view>
    </view>
    <!-- 轮播区域 -->
    <view class="swiper-box">
      <view class="swiper-bg"></view>
      <up-swiper :list="info.bannerList" keyName="picUrl" :radius="0" :height="`550rpx`" :indicator="true"
        indicatorMode="dot" indicatorInactiveColor="rgba(255, 255, 255, 0.2)" :autoplay="false"
        @click="swiperClick"></up-swiper>
    </view>
    <!-- 幸运盲盒 -->
    <view class="lucky-box">
      <view class="head">
        <view class="left">
          <text class="title">幸运盲盒</text>
          <text class="tip">丨消费免费领取盲盒</text>
        </view>
        <view class="right" @click="goBindBox">
          <text>规则说明</text>
          <up-icon name="arrow-right" color="#838385" size="24rpx"></up-icon>
        </view>
      </view>
      <image src="/static/images/lucky-box.png" mode="scaleToFill"
        style="margin-top:8rpx;width: 686rpx; height: 194rpx;" @click="goBindBox" />
    </view>
    <!-- 限时抢购 -->
    <view class="limit-box">
      <view class="head">
        <view class="left">
          <image style="width: 136rpx; height: 28rpx;" src="/static/images/icons/limit_title.png" mode="scaleToFill" />
          <text class="tip">丨限时狂欢惊喜价秒杀</text>
        </view>
        <view class="right" @click="goFlashSale">
          <up-count-down v-if="info.timeData !== null" :time="info.timeData" format="HH:mm:ss" autoStart millisecond
            @change="onChange" @finish="onActivityend">
            <view class="time">
              <view class="time__custom">
                <text class="time__custom__item">{{ timeData.hours > 9 ? timeData.hours : '0' + timeData.hours
                  }}</text>
              </view>
              <text class="time__doc">:</text>
              <view class="time__custom">
                <text class="time__custom__item">{{ timeData.minutes > 9 ? timeData.minutes : '0' + timeData.minutes
                  }}</text>
              </view>
              <text class="time__doc">:</text>
              <view class="time__custom">
                <text class="time__custom__item">{{ timeData.seconds > 9 ? timeData.seconds : '0' + timeData.seconds
                  }}</text>
              </view>
            </view>
          </up-count-down>
          <up-icon name="arrow-right" color="#838385" size="34rpx"></up-icon>
        </view>
      </view>
      <up-scroll-list :indicator="false">
        <view v-for="item in info.activityShopList" :key="item.id" class="item" @click="goActivityProductDetail(item)">
          <image :src="item.picUrl" style="width: 214rpx;height: 214rpx;"></image>
          <view class="price-box">
            <text class="present_price">￥{{ item.seckillPrice }}</text>
            <text class="original_price">￥{{ item.marketPrice }}</text>
          </view>
        </view>
      </up-scroll-list>
    </view>
    <!-- 商品 -->
    <view class="shop-box">
      <up-tabs :list="tabsList" @click="tabsChange" lineColor="#FFA618" lineHeight="6rpx" :activeStyle="{
        fontWeight: 600,
        fontSize: '32rpx',
        color: '#303133'
      }" :inactiveStyle="{
        fontWeight: 400,
        fontSize: '28rpx',
        color: '#303133'
      }"></up-tabs>
      <!-- 列表 -->
      <up-waterfall v-model="flowList" ref="uWaterfallRef">
        <template v-slot:left="{ leftList }">
          <view class="item left-item" v-for="(item, index) in leftList" :key="item.id"
            @click="goProductDetail(item.id)">
            <!-- 警告：微信小程序中需要hx2.8.11版本才支持在template中结合其他组件，比如下方的lazy-load组件 -->
            <up-lazy-load threshold="450" border-radius="10" height="332rpx" :image="item.picUrl"
              :index="index"></up-lazy-load>
            <view class="name">
              <text class="up-line-1">{{ item.name }}</text>
            </view>
            <view class="price-box">
              <text class="price">￥{{ item.price }}</text>
              <image src="/static/images/icons/add_car.png" style="width: 24rpx; height: 24rpx;" mode="scaleToFill" />
            </view>
          </view>
        </template>
        <template v-slot:right="{ rightList }">
          <view class="item right-item" v-for="(item, index) in rightList" :key="item.id"
            @click="goProductDetail(item.id)">
            <up-lazy-load threshold="450" border-radius="10" :image="item.picUrl" :index="index"></up-lazy-load>
            <view class="name">
              <text class="up-line-1">{{ item.name }}</text>
            </view>
            <view class="price-box">
              <text class="price">￥{{ item.price }}</text>
              <image src="/static/images/icons/add_car.png" style="width: 24rpx; height: 24rpx;" mode="scaleToFill" />
            </view>
          </view>
        </template>
      </up-waterfall>
      <up-loadmore bg-color="transparent" :status="shopInfo.loadStatus" @loadmore="getList"></up-loadmore>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.shop-page {
  min-height: 100vh;
  background-color: #F9F9F9;
  padding-bottom: 20rpx;

  // 导航栏
  & .navber {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100vw;
    // background-color: #000;

    & .tag-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: absolute;
      left: 32rpx;
      width: 108rpx;
    }

    & .title {
      display: flex;
      align-items: center;
      font-weight: 500;
      font-size: 32rpx;
      color: #FFFFFF;
    }
  }

  // 轮播
  & .swiper-box {
    position: relative;

    & .swiper-bg {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 9;
      height: 392rpx;
      width: 100vw;
      background: linear-gradient(180deg, #000000 0%, rgba(144, 147, 153, 0) 100%);
    }

    &::v-deep .u-swiper {
      & .u-swiper__indicator {
        bottom: 40rpx;

        & .u-swiper-indicator__wrapper__dot--active {
          width: 5px;
        }
      }
    }
  }

  // 幸运盲盒
  & .lucky-box {
    position: relative;
    z-index: 99;
    padding: 32rpx;
    margin-top: -21rpx;
    background-color: #F9F9F9;
    border-radius: 32rpx 32rpx 0rpx 0rpx;

    & .head {
      display: flex;
      align-items: center;
      justify-content: space-between;

      & .left {
        & .title {
          font-weight: 600;
          font-size: 32rpx;
          color: #303133;
        }

        & .tip {
          font-weight: 400;
          font-size: 20rpx;
          color: #838385;
        }
      }

      & .right {
        display: flex;
        align-items: center;
        font-weight: 400;
        font-size: 20rpx;
        line-height: 20rpx;
        color: #838385;

        &::v-deep .u-icon {
          margin-left: 4rpx;
          margin-top: 5rpx;
        }
      }
    }
  }

  // 限时抢购
  & .limit-box {
    padding: 0 32rpx;

    & .head {
      display: flex;
      align-items: center;
      justify-content: space-between;

      & .left {
        & .tip {
          font-weight: 400;
          font-size: 20rpx;
          color: #333333;
        }
      }

      & .right {
        display: flex;
        align-items: center;

        & .time {
          display: flex;
          align-items: center;

          &__custom {
            margin-top: 4px;
            width: 32rpx;
            height: 32rpx;
            background-color: #333333;
            border-radius: 2rpx;
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            justify-content: center;
            align-items: center;

            &__item {
              font-weight: 500;
              font-size: 20rpx;
              color: #FFFFFF;
              text-align: center;
            }
          }

          &__doc {
            color: #333333;
            padding: 0px 10rpx;
          }
        }

        &::v-deep .u-icon {
          margin-left: 12rpx;
          margin-top: 8rpx;
        }
      }
    }

    &::v-deep .u-scroll-list {
      margin-top: 30rpx;

      & .item {
        margin-right: 22rpx;
        width: 214rpx;
        background: #FFFFFF;
        overflow: hidden;
        border-radius: 9rpx;

        & image {
          border-radius: 9rpx;
        }

        & .price-box {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-top: 16rpx;
          margin-bottom: 12rpx;

          & .present_price {
            font-weight: 500;
            font-size: 24rpx;
            color: #333333;
          }

          & .original_price {
            padding-left: 8rpx;
            font-weight: 400;
            font-size: 20rpx;
            color: #90969E;
            text-decoration: line-through;
          }
        }
      }
    }
  }

  // 商品
  & .shop-box {
    padding: 0 32rpx;

    // tabs
    &::v-deep .u-tabs {
      & .u-tabs__wrapper__nav__line {
        border-radius: 50rpx 0rpx 50rpx 0rpx;
      }
    }

    // 列表
    & .u-waterfall {
      & .item {
        margin-top: 20rpx;
        padding-bottom: 24rpx;
        width: 332rpx;
        // height: 480rpx;
        background: #FFFFFF;
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        overflow: hidden;

        & .name {
          margin: 0 24rpx;
          padding-top: 24rpx;
          font-weight: 400;
          font-size: 28rpx;
          color: #333333;
        }

        & .price-box {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 0 24rpx;
          margin-top: 16rpx;
          // min-height: 332rpx;

          & .price {
            font-weight: 500;
            font-size: 32rpx;
            color: #333333;
          }
        }
      }
    }
  }
}
</style>